import { defineStore } from "pinia";
import { reqCategoryList1, reqCategoryList2, reqCategoryList3 } from "@/api/category";
import { ElMessage } from "element-plus";

// 三级分类数据类型
export interface CategoryListType {
    id: number;
    name: string;
    category1Id?: number;
    category2Id?: number;
}

export type CategoryType = CategoryListType[];
// 获取分类列表
// state类型
interface CategoryStateType {
    categoryList1: CategoryType;
    categoryId1: null | number;
    categoryList2: CategoryType;
    categoryId2: null | number;
    categoryList3: CategoryType;
    categoryId3: null | number;
}

export const useCategoryStore = defineStore("category", {
    // 一级分类
    state: (): CategoryStateType => {
        return {
            categoryList1: [], // 一级分类列表
            categoryId1: null, // 一级分类id
            categoryList2: [], // 二级分类列表
            categoryId2: null, // 二级分类id
            categoryList3: [], // 三级分类列表
            categoryId3: null, // 三级分类id
        };
    },
    actions: {
        // 获取一级分类
        async getCategoryList1() {
            try {
                this.categoryList1 = await reqCategoryList1();
            } catch (e) {
                ElMessage.error("获取一级分类失败");
            }
        },
        // 获取二级分类
        async getCategoryList2(categoryId1: number) {
            try {
                // 重置二级分类
                this.categoryList2 = [];
                this.categoryId2 = null;
                // 重置三级分类
                this.categoryList3 = [];
                this.categoryId3 = null;
                this.categoryList2 = await reqCategoryList2(categoryId1);
            } catch (e) {
                ElMessage.error("获取二级分类失败");
            }
        },
        // 获取三级分类
        async getCategoryList3(categoryId2: number) {
            try {
                // 重置三级分类
                this.categoryList3 = [];
                this.categoryId3 = null;
                this.categoryList3 = await reqCategoryList3(categoryId2);
            } catch (e) {
                ElMessage.error("获取三级分类失败");
            }
        },
        // 清空分类
        clearCategoryList() {
            this.categoryList1 = [];
            this.categoryId1 = null;
            this.categoryList2 = [];
            this.categoryId2 = null;
            this.categoryList3 = [];
            this.categoryId3 = null;
        },
    },
});
